/*
* Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/&gt;.
*
*/

#include "widget.h"
#include "ukuistylehelper/ukuistylehelper.h"
#include "windowmanager/windowmanager.h"

extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed);
double tranSparency = 0.7;

Widget::Widget(QWidget *parent) : QWidget (parent)
{
    /* 国际化 */
    initTranslation();

    //先仅注册托盘图标
    DataProcess::getInstance();
    createSystray();
}

Widget::~Widget()
{

}

void Widget::startBackgroundFunction()
{
    /* 初始化信号连接 */
    initConnect();

    /* 初始化主屏的X坐标 */
    InitializeHomeScreenGeometry();

    /* 获取屏幕可用高度区域 */
    GetsAvailableAreaScreen();

    /* 初始化动画 */
    initAimation();

    /* 主界面显示 */
    initLayout();

    /* 加载通知中心插件 */
    if (false == loadNotificationPlugin()) {
        qDebug() << "Notification center plug-in failed to load";
    }

    /* 加载快捷操作面板插件 */
    if (false == loadQuickOperationPlugin()) {
        qWarning() << "The shortcut panel failed to load";
    }

    /* 系统托盘栏显示 */
    createAction();

    //初始化Dbus服务
    registerDbusService();

    /* 安装事件过滤器 */
    installEventFilter(this);

    this->setWindowFlags(Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint);
    this->setProperty("useStyleWindowManager",false);

    qInfo() << "---------------------------主界面加载完毕---------------------------";
}

void Widget::initLayout()
{
    m_pMainQVBoxLayout = new QVBoxLayout;
    m_pMainQVBoxLayout->setContentsMargins(0,0,0,0);
    m_pMainQVBoxLayout->setSpacing(0);
    this->setLayout(m_pMainQVBoxLayout);
    return;
}

//设置托盘栏的图标
void Widget::sidebaractive()
{
    iconActivated(QSystemTrayIcon::Trigger);
}

//加载通知中心插件
bool Widget::loadNotificationPlugin()
{
    QDir pluginsDir;
    static bool installed = (QCoreApplication::applicationDirPath() == QDir(("/usr/bin")).canonicalPath());

    if (installed)
        pluginsDir = QDir(PLUGIN_INSTALL_DIRS);
    else
        pluginsDir = QDir(qApp->applicationDirPath() + "/plugins/ukui-sidebar-notification");

    pluginsDir.setFilter(QDir::Files);
    QPluginLoader pluginLoader(pluginsDir.absoluteFilePath("libnotification_plugin.so"));

    m_pNotificationPluginObject = pluginLoader.instance();
    if (nullptr == m_pNotificationPluginObject) {
        return false;
    }

    NotificationInterface* pNotificationPluginObject = qobject_cast<NotificationInterface*>(m_pNotificationPluginObject);
    if (nullptr == pNotificationPluginObject) {
        return false;
    }

    connect(m_pNotificationPluginObject, SIGNAL(Sig_onNewNotification()), this, SLOT(onNewNotification()));
    m_pMainQVBoxLayout->addWidget(pNotificationPluginObject->centerWidget(), 1);
    return true;
}

bool Widget::loadQuickOperationPlugin()
{
    QDir pluginsDir;
    static bool installed = (QCoreApplication::applicationDirPath() == QDir(("/usr/bin")).canonicalPath());

    if (installed)
        pluginsDir = QDir(PLUGIN_INSTALL_DIRS);
    else
        pluginsDir = QDir(qApp->applicationDirPath() + "/plugins/ukui-quick-operation-panel");

    pluginsDir.setFilter(QDir::Files);
    QPluginLoader pluginLoader(pluginsDir.absoluteFilePath("libshortcutPanel.so"));
    QObject *pPlugin = pluginLoader.instance();
    if (pPlugin == nullptr)
        return false;

    m_pQuickOperationInterface = dynamic_cast<quickOperationInterface *>(pPlugin);
    QWidget* shortCutWidget = m_pQuickOperationInterface->getQuickOperationWidget();
    m_pMainQVBoxLayout->addWidget(shortCutWidget);
    return true;
}

void Widget::registerDbusService()
{
    m_dbusService = new SidebarDbusService(this);
    connect(m_dbusService,&SidebarDbusService::showSidebarSignal,this,&Widget::bootOptionsFilter);
    MostGrandWidgetCoordinates();
}

void Widget::updateSidebarPosition(int height,int width)
{
    m_dbusService->setSidebarHeight(height);
    m_dbusService->setSidebarWidth(width);
}

//创建动作
void Widget::createAction()
{
    m_open = new QAction(QObject::tr("Open"), this);
    connect(m_open, &QAction::triggered, this, &Widget::OpenSidebarSlots);

    m_openSetUp = new QAction(QIcon::fromTheme("document-page-setup-symbolic", QIcon(SETTING_ICON)), QObject::tr("Set up notification center"), this);
    connect(m_openSetUp, &QAction::triggered, this, &Widget::OpenControlCenterSettings);

    m_trayIconMenu->addAction(m_open);
    m_trayIconMenu->addAction(m_openSetUp);

    connect(m_trayIcon, &QSystemTrayIcon::activated, this, &Widget::iconActivated);
}

//添加动作和创建 systray实例
void Widget::createSystray()
{
    m_trayIconMenu = new QMenu(this);
//    m_trayIconMenu->setProperty("iconHighlightEffectMode", 1);
    m_trayIconMenu->setProperty("doNotBlur",true);
    if (m_trayIconMenu == nullptr) {
        qWarning() << "分配空间trayIconMenu失败";
        return ;
    }

    registerSysTray();
}

void Widget::registerSysTray()
{
    if (QSystemTrayIcon::isSystemTrayAvailable() || m_registerCount > 10) {
        m_trayIcon = new QSystemTrayIcon(this);
        if (nullptr == m_trayIcon) {
            qWarning()<< "分配空间trayIcon失败";
            return ;
        }
        connect(m_trayIcon, &QSystemTrayIcon::activated, this, &Widget::clickTrayFunction);

        m_trayIcon->setIcon(QIcon::fromTheme("ukui-tool-symbolic", QIcon(TRAY_ICON)));
        m_trayIcon->setContextMenu(m_trayIconMenu);
        m_trayIcon->setToolTip(tr("ukui-sidebar"));
        m_trayIcon->setVisible(true);
    } else {
        if (m_registerCount <= 10) {
            m_intervalTime *=2;
            m_registerCount++;
            QTimer::singleShot(m_intervalTime,[this] {
                registerSysTray();
            });
        }
    }
}

void Widget::clickTrayFunction(QSystemTrayIcon::ActivationReason reason)
{
    if (!m_oneShotBool){
        disconnect(m_trayIcon, &QSystemTrayIcon::activated, this, &Widget::clickTrayFunction);
        emit startRun(reason);
        m_oneShotBool = true;
    }
}

//设置托盘栏的图标
void Widget::setIcon(QIcon icon)
{
    m_trayIcon->setIcon(icon);
    setWindowIcon(icon);
}

//设置activated信号
void Widget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    tranSparency = ControlCenterPersonGsetting::getInstance()->getTransparency();

    switch (reason) {
        case QSystemTrayIcon::Trigger: {
            if (this->isVisible()) {
                hideSidebar();
                //点击其他地方，隐藏侧边栏，收集数据
                pointDataStruct pointData;
                pointData.module = SYSTEM_TRAY_ICON;
                pointData.function = HIDE_SIDEBAR;
                DataProcess::getInstance()->sendData(pointData);
            } else {
                showSidebar();
                //点击托盘图标，展示侧边栏，收集数据
                pointDataStruct pointData;
                pointData.module = SYSTEM_TRAY_ICON;
                pointData.function = SHOW_SIDEBAR;
                DataProcess::getInstance()->sendData(pointData);
            }
            break;
        }
    case QSystemTrayIcon::Context:
        if (this->isVisible()) {
            m_trayIconMenu->hide();
            hideSidebar();
        }
        break;
   default:
        break;
    }
}

void Widget::initConnect()
{
    /* 监听屏幕分辨率是否变化 主频是否有变化 初始化屏幕宽高 和主屏起始X坐标值 */
    m_pDeskWgt = QApplication::desktop();

    connect(QApplication::primaryScreen(), &QScreen::geometryChanged, this, &Widget::onResolutionChanged);
    connect(QApplication::primaryScreen(), &QScreen::virtualGeometryChanged, this, &Widget::onVirtualGeometryChanged);

    connect(m_pDeskWgt, &QDesktopWidget::primaryScreenChanged, this, &Widget::primaryScreenChangedSLot);
    connect(m_pDeskWgt, &QDesktopWidget::screenCountChanged, this, &Widget::screenCountChangedSlots);


    /* 链接任务栏Dbus接口，获取任务栏点击信号 */
    QDBusConnection::sessionBus().connect(QString(),
                                          QString("/taskbar/click"),
                                          "com.ukui.panel.plugins.taskbar",
                                          "sendToUkuiDEApp", this, SLOT(ClickPanelHideSidebarSlots(void)));

    /* 监听任务栏位置更改，刷新侧边栏位置信息 */
    connect(PanelGsetting::getInstance(),&PanelGsetting::Sig_panelGsettingChanged,[=](QString key){
        if (key == "panelposition") {
            MostGrandWidgetCoordinates();
        }
    });

    /* 监听主题，更新所有的字体 */
    connect(StyleGsetting::getInstance(),&StyleGsetting::Sig_styleGsettingChanged,[=](QString key){
        if (UKUI_STYLE_FONT_KEY == key || UKUI_STYLE_FONT_SIZE_KEY ==key) {
            QFont font = this->font();
            for (auto widget : qApp->allWidgets()) {
                widget->setFont(font);
            }
        }
    });
}

//链接任务栏dbus获取高度的接口
int Widget::getPanelSize()
{
    return PanelGsetting::getInstance()->getPanelSize();
}

//获取任务栏状态位置
int Widget::getPanelPosition()
{
    return PanelGsetting::getInstance()->getPanelPosition();
}

//获取屏幕的可用区域高度和宽度
void Widget::GetsAvailableAreaScreen()
{
    //如果取不到任务栏的高度,还是优先获取桌面分辨率,可用区域
    if ((0 == getPanelSize())) {
        QScreen* pScreen = QGuiApplication::primaryScreen();
        QRect DeskSize = pScreen->availableGeometry();
        m_nScreenWidth = DeskSize.width();
        m_nScreenHeight = DeskSize.height();
    } else {
        //如果取到任务栏的高度,则取屏幕分辨率的高度
        QRect screenRect = QGuiApplication::primaryScreen()->geometry();
        m_nScreenWidth = screenRect.width();
        m_nScreenHeight = screenRect.height();
    }
    qDebug() << "主屏Width  --> " << m_nScreenWidth;
    qDebug() << "主屏Height --> " << m_nScreenHeight;
}

void Widget::initTranslation()
{
    m_pTranslator = new QTranslator;
    if (m_pTranslator->load(QLocale(), QLatin1String("ukui-sidebar"), QLatin1String("_"), QLatin1String("/usr/share/ukui-sidebar"))) {
        QApplication::installTranslator(m_pTranslator);
    } else {
        qDebug() << "cannot load translator " << QLocale::system().name() << ".qm!";
    }
}

void Widget::initAimation()
{
    m_pAnimationShow = new QPropertyAnimation(this, "geometry");
    m_pAnimationHide = new QPropertyAnimation(this, "geometry");

    connect(m_pAnimationHide, &QPropertyAnimation::finished, this, &Widget::hideAnimationFinish);
    connect(m_pAnimationShow, &QPropertyAnimation::valueChanged, this, &Widget::showAnimationAction);
    connect(m_pAnimationShow, &QPropertyAnimation::finished, this, &Widget::showAnimationFinish);

}

void Widget::showAnimationFinish()
{
    m_dbusService->setSidebarState(true);
    m_dbusService->setPresentSidebarWidth(SIDEBAR_WIDTH);
    SidebarCoreDbus::getInstance()->sendAnimationStatusSignal("show");
    QPainterPath path;
    auto rect = this->rect();
    rect.adjust(8, 8, -8, -8);
    path.addRoundedRect(rect, 12, 12);
    mostGrandWidget::getInstance()->setProperty("blurRegion", QRegion(path.toFillPolygon().toPolygon()));
    return;
}

//动画展开
void Widget::showAnimation()
{
    //此gsetting为清除锁屏未读消息，暂时放在这，以后会优化
    ScreensaverGsetting::getInstance()->setMessageNum(0);
    SidebarNotificationDbus::getInstance()->clearNotificationNum();

    NotificationInterface* pNotificationPluginObject = qobject_cast<NotificationInterface*>(m_pNotificationPluginObject);
    if (nullptr != pNotificationPluginObject) {
        pNotificationPluginObject->showNotification();       //当动画展开时给插件一个通知
    }

    int  AnimaStartSideBarSite[4];      //侧边栏动画开始位置
    int  AnimaStopSidebarSite[4];       //侧边栏动画结束位置

    switch (getPanelPosition())
    {
        case Widget::PanelDown :
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight - getPanelSize();
                //结束位置坐标
                AnimaStopSidebarSite[0]  = 0;
                AnimaStopSidebarSite[1]  = 0;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight  - getPanelSize();
            }
            break;
        case Widget::PanelUp:
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight  - getPanelSize();
                //结束位置坐标
                AnimaStopSidebarSite[0]  = 0;
                AnimaStopSidebarSite[1]  = 0;;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight - getPanelSize();
            }
            break;
        case Widget::PanelLeft:
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = -SIDEBAR_WIDTH;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight;
                //结束位置坐标
                AnimaStopSidebarSite[0]  = 0;
                AnimaStopSidebarSite[1]  = 0;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight;
            }
            break;
        case Widget::PanelRight:
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight;
                //结束位置坐标
                AnimaStopSidebarSite[0]  = 0;
                AnimaStopSidebarSite[1]  = 0;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight;
            }
            break;
        default:
            break;
    }
    m_pAnimationShow->setDuration(ANIMATIONSPEED);
    m_pAnimationShow->setStartValue(QRect(AnimaStartSideBarSite[0], AnimaStartSideBarSite[1], AnimaStartSideBarSite[2], AnimaStartSideBarSite[3]));
    m_pAnimationShow->setEndValue(QRect(AnimaStopSidebarSite[0], AnimaStopSidebarSite[1], AnimaStopSidebarSite[2], AnimaStopSidebarSite[3]));
    m_pAnimationShow->start();

    m_dbusService->setSidebarState(true);
    m_dbusService->setPresentSidebarWidth(SIDEBAR_WIDTH);

    //给通知中心发信号，开始左移动画
    SidebarCoreDbus::getInstance()->sendAnimationActionSignal(ANIMATIONSPEED,SIDEBAR_WIDTH);

}

void Widget::showAnimationAction(const QVariant &value)
{
//    QRect Rect = value.value<QRect>();
//    int x = Rect.x();
//    if (getPanelPosition() == Widget::PanelDown
//          || getPanelPosition() == Widget::PanelUp) {
//        mostGrandWidget::getInstance()->setProperty("blurRegion", QRegion(QRect(x, 8, SIDEBAR_WIDTH - 8, m_nScreenHeight - getPanelSize() - SIDEBAR_AND_PANEL_DISTANCE)));
//    } else {
//        mostGrandWidget::getInstance()->setProperty("blurRegion", QRegion(QRect(x, 8, SIDEBAR_WIDTH - 8, m_nScreenHeight - SIDEBAR_AND_PANEL_DISTANCE)));
//    }
}

//隐藏动画
void Widget::hideAnimation()
{
    NotificationInterface* pNotificationPluginObject = qobject_cast<NotificationInterface*>(m_pNotificationPluginObject);
    if (nullptr != pNotificationPluginObject) {
        pNotificationPluginObject->hideNotification();      //当动画隐藏时给插件一个通知
    }

    int  AnimaStartSideBarSite[4];                          //侧边栏动画开始位置
    int  AnimaStopSidebarSite[4];                           //侧边栏动画结束位置

    switch (getPanelPosition()) {
        case Widget::PanelDown :
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = 0;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight - getPanelSize();
                //结束位置坐标
                AnimaStopSidebarSite[0]  = 450;
                AnimaStopSidebarSite[1]  = 0;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight  - getPanelSize();
            }
            break;
        case Widget::PanelUp:
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = 0;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight  - getPanelSize();
                //结束位置坐标
                AnimaStopSidebarSite[0]  = 450;
                AnimaStopSidebarSite[1]  = 0;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight - getPanelSize();
            }
            break;
        case Widget::PanelLeft:
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = 0;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight;
                //结束位置坐标
                AnimaStopSidebarSite[0]  = -SIDEBAR_WIDTH;
                AnimaStopSidebarSite[1]  = 0;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight;
            }
            break;
        case Widget::PanelRight:
            {
                //起始位置的坐标
                AnimaStartSideBarSite[0] = 0;
                AnimaStartSideBarSite[1] = 0;
                AnimaStartSideBarSite[2] = SIDEBAR_WIDTH;
                AnimaStartSideBarSite[3] = m_nScreenHeight;
                //结束位置坐标
                AnimaStopSidebarSite[0]  = 450;
                AnimaStopSidebarSite[1]  = 0;
                AnimaStopSidebarSite[2]  = SIDEBAR_WIDTH;
                AnimaStopSidebarSite[3]  = m_nScreenHeight;
            }
            break;
        default:
            break;
    }
    m_pAnimationHide->setDuration(ANIMATIONSPEED);
    m_pAnimationHide->setStartValue(QRect(AnimaStartSideBarSite[0], AnimaStartSideBarSite[1], AnimaStartSideBarSite[2], AnimaStartSideBarSite[3]));
    m_pAnimationHide->setEndValue(QRect(AnimaStopSidebarSite[0], AnimaStopSidebarSite[1], AnimaStopSidebarSite[2], AnimaStopSidebarSite[3]));
    m_pAnimationHide->start();

    m_dbusService->setSidebarState(false);
    m_dbusService->setPresentSidebarWidth(0);

    //给通知中心发信号，开始左移动画
    SidebarCoreDbus::getInstance()->sendAnimationActionSignal(ANIMATIONSPEED, -SIDEBAR_WIDTH);

    return;
}

void Widget::hideAnimationFinish()
{
    m_dbusService->setSidebarState(false);
    m_dbusService->setPresentSidebarWidth(0);
    mostGrandWidget::getInstance()->hide();
    SidebarCoreDbus::getInstance()->sendAnimationStatusSignal("hide");
    return;
}

//当改变屏幕分辨率时重新获取屏幕分辨率
void Widget::onResolutionChanged(const QRect argc)
{
    Q_UNUSED(argc);
    qDebug() << "屏幕分辨率发生变化";
    GetsAvailableAreaScreen();            //获取屏幕可用高度区域
    InitializeHomeScreenGeometry();
    MostGrandWidgetCoordinates();

    //若侧边栏是隐藏状态 return
    if (!this->isVisible()) {
        return;
    }
    hideSidebar();
    return;
}

//当屏幕位置变化时，不隐藏，只调整位置
void Widget::onVirtualGeometryChanged(const QRect argc)
{
    Q_UNUSED(argc);
    qDebug() << "屏幕分辨率发生变化";
    GetsAvailableAreaScreen();            //获取屏幕可用高度区域
    InitializeHomeScreenGeometry();
    MostGrandWidgetCoordinates();
}

/* 主屏发生变化槽函数 */
void Widget::primaryScreenChangedSLot()
{
    qDebug() << "主屏发生变化";
    GetsAvailableAreaScreen();
    InitializeHomeScreenGeometry();
    return;
}

/* 屏幕数量改变时对应槽函数 */
void Widget::screenCountChangedSlots(int count)
{
    Q_UNUSED(count);
    qDebug() << "屏幕数量发生变化";
    GetsAvailableAreaScreen();
    InitializeHomeScreenGeometry();
    return;
}

/* 接受任务栏点击信号，当任务栏点击左键时，关闭任务栏 */
void Widget::ClickPanelHideSidebarSlots()
{
    if (this->isVisible()) {
        hideSidebar();
        //点击任务栏，隐藏侧边栏，收集数据
        pointDataStruct pointData;
        pointData.module = PANEL;
        pointData.function = HIDE_SIDEBAR;
        DataProcess::getInstance()->sendData(pointData);
    }
    return;
}

/* 右键菜单打开侧边栏槽函数 */
void Widget::OpenSidebarSlots()
{
    showSidebar();
    //右键托盘图标，打开侧边栏，收集数据
    pointDataStruct pointData;
    pointData.module = SYSTEM_TRAY_ICON_MENU;
    pointData.function = SHOW_SIDEBAR;
    DataProcess::getInstance()->sendData(pointData);
    return;
}

/* 打开控制中心的通知中心 */
void Widget::OpenControlCenterSettings()
{
    QProcess p(0);
    p.startDetached("ukui-control-center -m Notice");
    p.waitForStarted();
    return;
}

/* 初始化主屏的X坐标 */
void Widget::InitializeHomeScreenGeometry()
{
    if (QGuiApplication::primaryScreen()) {
        m_nScreen_x = QGuiApplication::primaryScreen()->geometry().x();
        m_nScreen_y = QGuiApplication::primaryScreen()->geometry().y();
    } else {
        QList<QScreen*> screen = QGuiApplication::screens();
        int count = m_pDeskWgt->screenCount();
        if (count > 1) {
            m_nScreen_x = screen[0]->geometry().x();
            m_nScreen_y = screen[0]->geometry().y();
        } else {
            m_nScreen_x = 0;
            m_nScreen_y = 0;
        }
    }
    return;
}

/* 根据任务栏位置调整侧边栏位置 */
void Widget::MostGrandWidgetCoordinates()
{
    switch (getPanelPosition()) {
    case Widget::PanelDown :
    {
        QString platform = QGuiApplication::platformName();
        if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive))
        {
            mostGrandWidget::getInstance()->setFixedSize(SIDEBAR_WIDTH, m_nScreenHeight - getPanelSize());
            mostGrandWidget::getInstance()->move(m_nScreen_x + m_nScreenWidth - SIDEBAR_WIDTH, m_nScreen_y);
        } else {
            kdk::WindowManager::setGeometry(mostGrandWidget::getInstance()->windowHandle(),QRect(m_nScreen_x + m_nScreenWidth - SIDEBAR_WIDTH,
                                                                                                 m_nScreen_y,
                                                                                                 SIDEBAR_WIDTH,
                                                                                                 m_nScreenHeight - getPanelSize()));
        }

        updateSidebarPosition(m_nScreenHeight - getPanelSize() - SIDEBAR_AND_PANEL_DISTANCE, SIDEBAR_WIDTH);

    }
        break;
    case Widget::PanelUp:
    {
        QString platform = QGuiApplication::platformName();
        if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive))
        {
            mostGrandWidget::getInstance()->setFixedSize(SIDEBAR_WIDTH, m_nScreenHeight - getPanelSize());
            mostGrandWidget::getInstance()->move(m_nScreen_x + m_nScreenWidth - SIDEBAR_WIDTH, getPanelSize() + m_nScreen_y);
        } else {
            kdk::WindowManager::setGeometry(mostGrandWidget::getInstance()->windowHandle(),QRect(m_nScreen_x + m_nScreenWidth - SIDEBAR_WIDTH,
                                                                                                 getPanelSize() + m_nScreen_y,
                                                                                                 SIDEBAR_WIDTH,
                                                                                                 m_nScreenHeight - getPanelSize()));
        }

        updateSidebarPosition(m_nScreenHeight - getPanelSize() - SIDEBAR_AND_PANEL_DISTANCE, SIDEBAR_WIDTH);

    }
        break;
    case Widget::PanelLeft:
    {
        QString platform = QGuiApplication::platformName();
        if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive))
        {
            mostGrandWidget::getInstance()->setFixedSize(SIDEBAR_WIDTH, m_nScreenHeight);
            mostGrandWidget::getInstance()->move(m_nScreen_x + getPanelSize(), m_nScreen_y);
        } else {
            kdk::WindowManager::setGeometry(mostGrandWidget::getInstance()->windowHandle(),QRect(m_nScreen_x + getPanelSize(),
                                                                                                 m_nScreen_y,
                                                                                                 SIDEBAR_WIDTH,
                                                                                                 m_nScreenHeight));
        }
        updateSidebarPosition(m_nScreenHeight - SIDEBAR_AND_PANEL_DISTANCE, SIDEBAR_WIDTH);

    }
        break;
    case Widget::PanelRight:
    {
        QString platform = QGuiApplication::platformName();
        if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive))
        {
            mostGrandWidget::getInstance()->setFixedSize(SIDEBAR_WIDTH, m_nScreenHeight);
            mostGrandWidget::getInstance()->move(m_nScreen_x + m_nScreenWidth - SIDEBAR_WIDTH - getPanelSize(), m_nScreen_y);
        } else {
            kdk::WindowManager::setGeometry(mostGrandWidget::getInstance()->windowHandle(),QRect(m_nScreen_x + m_nScreenWidth - SIDEBAR_WIDTH - getPanelSize(),
                                                                                                 m_nScreen_y,
                                                                                                 SIDEBAR_WIDTH,
                                                                                                 m_nScreenHeight));
        }

        updateSidebarPosition(m_nScreenHeight - SIDEBAR_AND_PANEL_DISTANCE, SIDEBAR_WIDTH);

    }
        break;
    default:
        break;
    }
}

//当没展开时，来了新通知,更换托盘图标为未读消息图标
void Widget::onNewNotification()
{
    if (!this->isVisible()) {
        setIcon(QIcon::fromTheme("ukui-tool-box-null-symbolic", QIcon(TRAY_NULL_ICON)));
    }
    return;
}

/* 过滤终端命令 */
void Widget::bootOptionsFilter(QString opt)
{
    if (m_oneShotBool){
        if (opt == "-state" ) {
            if (this->isVisible()) {
                hideSidebar();
                //终端命令，隐藏侧边栏，收集数据
                pointDataStruct pointData;
                pointData.module = SHELL_COMMAND;
                pointData.function = HIDE_SIDEBAR;
                DataProcess::getInstance()->sendData(pointData);
            } else {
                showSidebar();
                //终端命令，打开侧边栏，收集数据
                pointDataStruct pointData;
                pointData.module = SHELL_COMMAND;
                pointData.function = SHOW_SIDEBAR;
                DataProcess::getInstance()->sendData(pointData);
            }
        } else if (opt == "-h" || opt == "-hide") {
            if(this->isVisible()) {
                hideSidebar();
                //终端命令，隐藏侧边栏，收集数据
                pointDataStruct pointData;
                pointData.module = SHELL_COMMAND;
                pointData.function = HIDE_SIDEBAR;
                DataProcess::getInstance()->sendData(pointData);
            }
        } else if (opt == "-s" || opt == "-show") {
            if(!this->isVisible()) {
                showSidebar();
                //终端命令，打开侧边栏，收集数据
                pointDataStruct pointData;
                pointData.module = SHELL_COMMAND;
                pointData.function = SHOW_SIDEBAR;
                DataProcess::getInstance()->sendData(pointData);
            }
        }
    }
}

void Widget::hideSidebar()
{
    qDebug()<<"隐藏侧边栏";
    m_bShowFlag = false;
    mostGrandWidget::getInstance()->topLevelWidget()->setProperty("blurRegion", QRegion(QRect(1, 1, 1, 1)));
    hideAnimation();

}

void Widget::showSidebar()
{
    qDebug()<<"展示侧边栏";
    mostGrandWidget::getInstance()->topLevelWidget()->setProperty("blurRegion", QRegion(QRect(1, 1, 1, 1)));
    mostGrandWidget::getInstance()->show();
    GetsAvailableAreaScreen();            //获取屏幕可用高度区域
    InitializeHomeScreenGeometry();
    MostGrandWidgetCoordinates();
    showAnimation();
    m_bShowFlag = true;
    setIcon(QIcon::fromTheme("ukui-tool-symbolic", QIcon(TRAY_ICON)));
}

void Widget::setoneShotBool(bool state)
{
    m_oneShotBool = state;
}

/* 事件过滤器 */
bool Widget::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == this) {
        if (event->type() == QEvent::WindowDeactivate \
                && m_bShowFlag) {
            hideSidebar();
            //失去焦点，隐藏侧边栏，收集数据
            pointDataStruct pointData;
            pointData.module = LOSE_FOCUS;
            pointData.function = HIDE_SIDEBAR;
            DataProcess::getInstance()->sendData(pointData);
            return true;
        } else if (event->type() == QEvent::StyleChange) {
            return true;
        }
    }
    if (!isActiveWindow() && m_bShowFlag) {
        activateWindow();
    }
    return false;
}

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);
    QPainterPath rectPath;

    rectPath.addRoundedRect(this->rect().adjusted(9, 9, -9, -9), 12, 12);

    QPixmap pixmap(this->rect().size());
    pixmap.fill(Qt::transparent);
    QPainter pixmapPainter(&pixmap);
    pixmapPainter.setRenderHint(QPainter::Antialiasing);
    pixmapPainter.setPen(Qt::transparent);
    pixmapPainter.setBrush(Qt::black);
    pixmapPainter.setOpacity(0.65);
    pixmapPainter.drawPath(rectPath);
    pixmapPainter.end();

    QImage img = pixmap.toImage();
    qt_blurImage(img, 14, false, false);

    pixmap = QPixmap::fromImage(img);
    QPainter pixmapPainter2(&pixmap);
    pixmapPainter2.setRenderHint(QPainter::Antialiasing);
    pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear);
    pixmapPainter2.setPen(Qt::transparent);
    pixmapPainter2.setBrush(Qt::transparent);
    pixmapPainter2.drawPath(rectPath);

    p.drawPixmap(this->rect(), pixmap, pixmap.rect());
    p.save();
    QColor color = qApp->palette().color(QPalette::Base);
    color.setAlphaF(tranSparency);
    p.fillPath(rectPath, color);
    p.restore();
    QWidget::paintEvent(event);
}
